import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/page/imageview/StudentCourseView.dart';
import 'package:FineArt/utils/platform_util.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'dart:convert' as convert;

import 'class_api.dart';
import 'course_api.dart';

class MqttService
{
  MqttService._internal();

  static MqttServerClient mqttClient;


  static String _userTopic()
  {
    String uid = SPUtils.getUID();
    String topic =  "W0FIbOArG5CnyVViNU8CE3YbHt1u3Jyn/pcapi/person/" + uid+"/";
    return topic;
  }

  static String courseTopic(int courseid)
  {
    String topic =  "W0FIbOArG5CnyVViNU8CE3YbHt1u3Jyn/pcapi/course/" + courseid.toString() + "/";
    return topic;
  }

   static startMqtt(BuildContext context) async {
    print("==>start mqtt");
    String name = SPUtils.getUsername();
    String uuid = await PlatformUtil.uuid(name);


    MqttServerClient client =
    MqttServerClient.withPort('8.136.199.147',uuid, 8081);
    final connMessage = MqttConnectMessage()
        .keepAliveFor(60)
        .startClean();
    client.connectionMessage = connMessage;
    client.onSubscribeFail = (message){print("==>sub failed:" + message);};
    client.onSubscribed = (message){print("==>sub suc:"+message);};
    client.onUnsubscribed = (message){print("==>unsub:"+message);};
    try {
      await client.connect();
    } catch (e) {
      print('Exception: $e');
      client.disconnect();
    }


    client.subscribe(_userTopic(), MqttQos.atLeastOnce);

    client.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
      final MqttPublishMessage message = c[0].payload;
      final payload =
      MqttPublishPayload.bytesToStringAsString(message.payload.message);

      String topic = c[0].topic.toString();
      print("==>topic:"+topic);
      if (topic.contains("pcapi/person/"))
      {
        Map<String,dynamic> body = convert.jsonDecode(payload);
        String cmd = body["cmd"];
        if (cmd == "create")
        {
          int courseid = body["courseid"];
          int assettype = body["assettype"];

          Course course = new Course(Id: courseid, AssetType: assettype);


          CourseApi().courseInfo(course.Id).then((res1) {
            if (res1.code == 200) {
              CourseInfo info = res1.data;
              //2：根据资源ID获取资源详情
              ResourceApi()
                  .resourceDetail(info.AssetId, course.AssetType)
                  .then((res2) {
                if (res2.code == 200) {
                  ResourceDetail detail = res2.data;
                  if (detail.type == 1 || detail.type == 5001) //图片
                      {
                    ResourceInfo1 info1 =
                    detail.info as ResourceInfo1;
                    String role = SPUtils.getRole();
                    if (role != "teacher") {
                      StudentCourseView.Jump2CourseView(info1.hdurl, course.Id, context);
                    }
                  }
                }
              });
            }
          });
        }
      }
      else if (topic.contains("pcapi/course/"))
      {
        Map<String,dynamic> body = convert.jsonDecode(payload);
        String cmd = body["cmd"];
        if (cmd == "close")
        {
          Navigator.of(context).pop();
        }
      }

      print('Received message:$payload from topic: ${c[0].topic}>');
    });

    mqttClient = client;
  }

}